package com.wang.web3;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wang.web3.adapter.WalletAdapter;
import com.wang.web3.base.Constant;
import com.wang.web3.bean.ContractAddressBean;
import com.wang.web3.bean.ContractBean;
import com.wang.web3.bean.TianWallet;
import com.wang.web3.bean.TianWallets;
import com.wang.web3.bean.WalletBean;
import com.wang.web3.data.service.ICallBackListener;
import com.wang.web3.data.service.impl.ApiServiceImpl;
import com.wang.web3.utils.SPUtils;

import org.web3j.crypto.WalletUtils;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.Web3jFactory;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.response.EthGetBalance;
import org.web3j.protocol.http.HttpService;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;


public class HomeFragment extends Fragment implements View.OnClickListener,WalletAdapter.PersonHolderListener{
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    boolean havs = false;
    String lock;
    int currentpostion;
    WalletAdapter walletAdapter;

    public HomeFragment() {
        // Required empty public constructor
    }

    Button mCreatBtn,mIntoBtn;
    TextView tvInfo,tvBlance;
    RecyclerView mWalletRv;
    Gson gson = new Gson();
    TianWallets wallets;
    Web3j web3;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HomeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        tvInfo = view.findViewById(R.id.info);
        mCreatBtn = view.findViewById(R.id.mCreatBtn);
        mIntoBtn = view.findViewById(R.id.mIntoBtn);
        mWalletRv = view.findViewById(R.id.mWalletRv);
        tvBlance = view.findViewById(R.id.blance);
        mCreatBtn.setOnClickListener(this);
        mIntoBtn.setOnClickListener(this);
        init();
        web3 = Web3jFactory.build(new HttpService(Constant.URL));
        testBlance();
        return view;
    }

    private void init() {
        List<WalletBean> list = new ArrayList<>();
        String filePath = Environment.getExternalStorageDirectory().getAbsolutePath().toString() + Constant.WalletUri;
        File dis = new File(filePath);
        if (!dis.exists()){
            dis.mkdirs();
        }

        lock = (String) SPUtils.get(getActivity(),Constant.WALLETLOCKADDRESS,"");
        if (lock.equals("")){
            tvInfo.setText("暂未绑定账户，点击账户进行绑定");
            tvInfo.setVisibility(View.VISIBLE);
        }else{
            tvInfo.setVisibility(View.GONE);
            getCore();
        }

        File[] files = dis.listFiles();
        if (files != null && files.length > 0){
            //test
            mCreatBtn.setVisibility(View.VISIBLE);
            mIntoBtn.setVisibility(View.VISIBLE);

            for (File file : files) {
                if (file.isDirectory()){//检查此路径名的文件是否是一个目录(文件夹)
                } else {
                    String fileName = file.getName();
                    Log.e("Tag","ss" + file);
                    try {

                        FileInputStream inputStream = new FileInputStream(filePath + "/" + fileName);

                        byte temp[] = new byte[1024];
                        StringBuilder sb = new StringBuilder("");
                        int len = 0;
                        while ((len = inputStream.read(temp)) > 0){
                            sb.append(new String(temp, 0, len));
                        }
                        String string = sb.toString();
                        WalletBean walletBean = gson.fromJson(string, WalletBean.class);
                        walletBean.setUri(filePath + "/" + fileName);
                        list.add(walletBean);

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }else{
            mCreatBtn.setVisibility(View.VISIBLE);
            mIntoBtn.setVisibility(View.VISIBLE);
            tvInfo.setVisibility(View.VISIBLE);
        }

        String ss = (String) SPUtils.get(getActivity(),Constant.WalletKey,"");

        if (!ss.equals("")){
            wallets = gson.fromJson(ss, TianWallets.class);
        }else {
            wallets = new TianWallets(new ArrayList<TianWallet>());
        }


         for (int i = 0; i < list.size(); i++) {
             havs =false;

            for (int j = 0; j < wallets.getTianWallets().size(); j++) {
                 if (("0x"+list.get(i).getAddress()).equals(wallets.getTianWallets().get(j).getAdress())){
                     havs = true;
                    continue;
                }
            }

            if (!havs){
                TianWallet tianWallet = new TianWallet("Account" + i,"0x" + list.get(i).getAddress(),list.get(i).getUri());
                wallets.getTianWallets().add(tianWallet);
            }
        }



        walletAdapter = new WalletAdapter(wallets.getTianWallets(),this);
        mWalletRv.setLayoutManager(new LinearLayoutManager(getActivity()));
        mWalletRv.setAdapter(walletAdapter);
//        String fileName = WalletUtils.generateNewWalletFile("password",new File(filePath),false);
    }

    //获取合约地址
    private void getCore() {

        try {
            InputStream inputStream = getActivity().getAssets().open("contract-address.json");
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufr = new BufferedReader(inputStreamReader);//缓冲
            StringBuffer sb = new StringBuffer();
            String line;
            while((line = bufr.readLine())!=null){
                sb.append(line);
                System.out.println(line);
            }

            SPUtils.put(getActivity(),Constant.CONTRACTADDRESS,sb.toString());

            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


//        ApiServiceImpl.getInstence().contractAddress(new ICallBackListener() {
//            @Override
//            public void onSuccess(String string) {
//                ContractAddressBean contractAddressBean = gson.fromJson(string, ContractAddressBean.class);
//                SPUtils.put(getActivity(),Constant.CONTRACTADDRESS,string);
//            }
//
//            @Override
//            public void onFaild(String string) {
//
//            }
//        });
    }

    @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.mCreatBtn:
                     getActivity().startActivity(new Intent(getActivity(),CreateWalletActivity.class));
                    break;
                case R.id.mIntoBtn:
                    startActivityForResult(new Intent(getActivity(),IntoWalletActivity.class),0);
                    break;
            }
        }

    @Override
    public void onPersonItemClicked(View v, MotionEvent event, int position) {

        if (lock.equals("")){
            currentpostion = position;
            Intent intent = new Intent(getActivity(),LockWalletActivity.class);
            intent.putExtra("address",wallets.getTianWallets().get(position).getAdress());
            startActivityForResult(intent,0);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null){
            return;
        }
        if (resultCode == 0){
            wallets.getTianWallets().get(currentpostion).setInfo("该账号已绑定");
            havs = true;
            tvInfo.setVisibility(View.GONE);
            testBlance();
            lock = (String) SPUtils.get(getActivity(),Constant.WALLETLOCKADDRESS,"");
            walletAdapter.notifyDataSetChanged();
        }else if (resultCode == 1){
            String ss = (String) SPUtils.get(getActivity(),Constant.WalletKey,"");

            if (!ss.equals("")){
                wallets = gson.fromJson(ss, TianWallets.class);
            }else {
                wallets = new TianWallets(new ArrayList<TianWallet>());
            }
            walletAdapter.setNewData(wallets.getTianWallets());
            walletAdapter.notifyDataSetChanged();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what){
                //部署合约
                case 0:
//                    mtvTestDeploy.setText("getContractAddress----" + kittyAccessControl.getContractAddress());
                    break;
                //查询余额
                case 1:
                    String sb = (String) msg.obj;
                    tvBlance.setText("绑定账户余额：" + sb);
                    break;
            }
            return false;
        }
    }
    );

    //查询余额
    private void testBlance() {

        final String wallet = (String) SPUtils.get(getActivity(),Constant.WALLETLOCKADDRESS,"");
        if (wallet.equals("")){
            return;
        }
        // //获取余额
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    TianWallet tianWallet = gson.fromJson(wallet,TianWallet.class);
                    EthGetBalance ethGetBalance1 = web3.ethGetBalance(tianWallet.getAdress(), DefaultBlockParameterName.LATEST).send();
                    BigDecimal balance = new BigDecimal(ethGetBalance1.getBalance().divide(new BigInteger("10000000000000")).toString());
                    BigDecimal nbalance = balance.divide(new BigDecimal("100000"), 8, BigDecimal.ROUND_DOWN);
                    Message message = Message.obtain();
                    message.what = 1;
                    message.obj = nbalance + "eth";
                    mHandler.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

